const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 购物车商品数量
    cartNum: 0,
    // 购物车内的商品
    carts: [],
    // 显示购物车
    showCart: false,
    // 所有的食品数据
    foods: [],
    // 当前显示的食品列表
    currFoods: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow (options) {
    this.getFoods();
    this.getCartList();
  },

  render(e) {
    let id = e.currentTarget.dataset.id;
    let food = this.data.foods.find(item => {
      return item.id == id;
    });
    this.setData({
      currFoods: food.foods
    })
  },

  toggleShowCart() {
    this.setData({
      showCart: !this.data.showCart
    })
  },

  clearCart() {
    let url = '/cart/clearCart';
    app.ajax(url,null,res=> {
      this.setData({
        showCart: false,
        cartNum: 0,
        carts: []
      })
    })
  },

  // 添加到购物车
  addCart(e) {
    let url = '/cart/addCart';
    let id = e.currentTarget.dataset.id;
    // 根据id找到对应的商品
    let food = this.data.currFoods.find(item=> {
      return item.item_id == id;
    })
    app.ajax(url,{id},res=> {
      this.setData({
        cartNum: this.data.cartNum + 1
      })
      console.log(res);
      this.setData({
        carts: [
          ...this.data.carts,
          food
        ]
      })
      console.log(this.data.carts);
    })
  },
  // 去结算
  count() {
    let url = '/order/createOrder';
    let params = [];
    let carts = this.data.carts;
    for (let cart of carts) {
      params.push({
        id: cart.item_id,
        buyNum: cart.buyNum || 1
      })
    }
    app.ajax(url, { carts: params}, res=> {
      this.setData({
        cartNum: 0,
        carts: []
      })
      wx.showModal({
        content: res.msg,
        showCancel: false,
        success:(res)=> {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/order/order'
            })
          }
        }
      })
    })
  },

  getCartList() {
    let url = '/cart/cartList';
    let data = {};
    app.ajax(url,data,res=> {
      this.setData({
        cartNum: res.list.length,
        carts: res.list
      })
    })
  },

  getFoods() {
    let url = '/food/foodList';
    let data = {};
    app.ajax(url, data, res=> {
      this.setData({
        foods: res.list,
        currFoods: res.list[0].foods
      })
    })
  }
})